package com.tduck.cloud.api.web.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.tduck.cloud.api.annotation.Login;
import com.tduck.cloud.common.util.Result;
import com.tduck.cloud.project.entity.ImageAttachmentEntity;
import com.tduck.cloud.project.mapper.ImageAttachmentMapper;
import com.tduck.cloud.storage.cloud.OssStorageFactory;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author : smalljop
 * @description : 上传文件
 * @create : 2020-11-27 14:00
 **/
@RestController
@RequiredArgsConstructor
public class UploadFileController {


    @Autowired
    private ImageAttachmentMapper imageAttachmentMapper;

    @Value("${picUploadBaseUrl}")
    private  String picUploadBaseUrl;

    /**
     * 上传用户文件
     * <p>
     * 用户Id MD5加密 同一个用户的文件放在一个目录下
     *
     * @param file
     * @param userId
     * @return
     * @throws IOException
     */
    @Login
    @PostMapping("/user/file/upload")
    public Result<String> uploadUserFile(@RequestParam("file") MultipartFile file, @RequestAttribute Long userId) throws IOException {
        /*String path = new StringBuffer(SecureUtil.md5(String.valueOf(userId)))
                .append(CharUtil.SLASH)
                .append(IdUtil.simpleUUID())
                .append(CharUtil.DOT)
                .append(FileUtil.extName(file.getOriginalFilename())).toString();
        String url = OssStorageFactory.build().upload(file.getInputStream(), path);
        return Result.success(url);*/
        String picUrls="";
        String uploadPath = picUploadBaseUrl;
        System.out.println("=====picUploadBaseUrl"+picUploadBaseUrl);
        System.out.println("=====uploadPath"+uploadPath);
        File uploadDirectory = new File(uploadPath);
        if (uploadDirectory.exists()) {
            if (!uploadDirectory.isDirectory()) {
                uploadDirectory.delete();
            }
        } else {
            uploadDirectory.mkdir();
        }
        System.out.println("=====file"+file);
        String fileName = file.getOriginalFilename();
        //判断是否有文件且是否为图片文件
        if(fileName!=null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {
            String picBaseUrl="/images/" + UUID.randomUUID().toString()+ getFileType(fileName);
            String picUrl=uploadPath +picBaseUrl;
            //创建输出文件对象
            File outFile = new File(picUrl);
            //拷贝文件到输出文件对象
            FileUtils.copyInputStreamToFile(file.getInputStream(), outFile);
            ImageAttachmentEntity t = new ImageAttachmentEntity();
            t.setName(fileName);
            t.setKey("");
            t.setPath(picUrl);
            t.setCreateTime(new Date());
            t.setMediaType(file.getContentType());
            t.setSize(file.getSize());
            imageAttachmentMapper.insert(t);
            picUrls+=picBaseUrl+",";
        }

        System.out.println("=====picUrls"+picUrls);
        picUrls = picUrls.substring(0, picUrls.length() - 1);
        System.out.println("=====picUrls"+picUrls);
        return Result.success(picUrls);
    }


    /**
     * 项目文件上传
     *
     * @param file
     * @param projectKey
     * @return
     * @throws IOException
     */
    @PostMapping("/project/file/upload/{projectKey}")
    public Result<String> uploadProjectFile(@RequestParam("file") MultipartFile file, @PathVariable("projectKey") String projectKey) throws IOException {
//        String path = new StringBuffer(SecureUtil.md5(projectKey))
//                .append(CharUtil.SLASH)
//                .append(IdUtil.simpleUUID())
//                .append(CharUtil.DOT)
//                .append(FileUtil.extName(file.getOriginalFilename())).toString();
//        String url = OssStorageFactory.build().upload(file.getInputStream(), path);
        String picUrls="";
        String uploadPath = picUploadBaseUrl;
        System.out.println("=====picUploadBaseUrl"+picUploadBaseUrl);
        System.out.println("=====uploadPath"+uploadPath);
        File uploadDirectory = new File(uploadPath);
        if (uploadDirectory.exists()) {
            if (!uploadDirectory.isDirectory()) {
                uploadDirectory.delete();
            }
        } else {
            uploadDirectory.mkdir();
        }
        System.out.println("=====file"+file);
        String fileName = file.getOriginalFilename();
        //判断是否有文件且是否为图片文件
        if(fileName!=null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {
            String picBaseUrl="/images/" + UUID.randomUUID().toString()+ getFileType(fileName);
            String picUrl=uploadPath +picBaseUrl;
            //创建输出文件对象
            File outFile = new File(picUrl);
            //拷贝文件到输出文件对象
            FileUtils.copyInputStreamToFile(file.getInputStream(), outFile);
            ImageAttachmentEntity t = new ImageAttachmentEntity();
            t.setName(fileName);
            t.setKey(projectKey);
            t.setPath(picUrl);
            t.setCreateTime(new Date());
            t.setMediaType(file.getContentType());
            t.setSize(file.getSize());
            imageAttachmentMapper.insert(t);
            picUrls+=picBaseUrl+",";
        }

        System.out.println("=====picUrls"+picUrls);
        picUrls = picUrls.substring(0, picUrls.length() - 1);
        System.out.println("=====picUrls"+picUrls);
        return Result.success(picUrls);
    }




    private Boolean isImageFile(String fileName) {
        String[] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp", ".pdf", ".xlsx", ".xls",".doc", ".docx"};
        if (fileName == null) {
            return false;
        }
        fileName = fileName.toLowerCase();
        for (String type : img_type) {
            if (fileName.endsWith(type)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件后缀名
     *
     * @param fileName
     * @return
     */
    private String getFileType(String fileName) {
        if (fileName != null && fileName.indexOf(".") >= 0) {
            return fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        return "";
    }
}
